package com.fingard.dsp.bank.directbank.bea11;

import com.fingard.constant.Format;
import com.fingard.dsp.bank.directConfig.FtpSet;
import com.fingard.dsp.bank.directConfig.TaskTimerSet;
import com.fingard.dsp.bank.directbank.bankInterface.IScheduleTask;
import com.fingard.io.FileHelper;
import com.fingard.net.ConnState;
import com.fingard.net.FtpPortClient;
import com.fingard.net.FtpReceiver;
import com.fingard.net.SftpPortClient;
import com.fingard.text.StringHelper;

import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.StringReader;
import java.math.BigDecimal;
import java.text.MessageFormat;
import java.util.Calendar;
import java.util.Date;

public class BEA11ScheduleTask extends BEA11Base implements IScheduleTask {
    public boolean isRunded = false;

    @Override
    public void execTask(TaskTimerSet timerSet) {
        try {
            if (timerSet.taskNameList.toLowerCase().contains("pushdata")) {
                pushData();
            }
        } catch (Exception ex) {
            this.WriteBankLogLn(ex);
        }
    }

    public void pushData() throws IOException {
        try {
            // 获取日切时间判断是否可以执行定时任务
            Date tmpDateNow = new Date();
            String dayCutTime = getBankConfig().getValueAsString("dayCutTime");
            if (StringHelper.hasAnyChar(dayCutTime)) {
                Calendar calendar = Calendar.getInstance();
                calendar.setTime(tmpDateNow);

                Calendar endCalendar = Calendar.getInstance();
                String time = String.format("%4s", dayCutTime.replace(":", "")).replace(" ", "0");
                endCalendar.setTime(Format.Time6Format.parse(time + "00"));
                endCalendar.add(Calendar.MINUTE, 1);
                String endDateTime = endCalendar.get(Calendar.HOUR_OF_DAY) + ":" + String.format("%2s",endCalendar.get(Calendar.MINUTE)).replace(" ", "0");

                int tmpDayCutTime = Integer.parseInt(dayCutTime.replace(":", ""));
                WriteBankLogLn("日切时间范围:[" + dayCutTime + "~" + endDateTime + "].");
                int tmpTimeNow = calendar.get(Calendar.HOUR_OF_DAY) * 100 + calendar.get(Calendar.MINUTE);
                String tmpTimeEnd = calendar.get(Calendar.HOUR_OF_DAY) + ":" + calendar.get(Calendar.MINUTE);
                WriteBankLogLn("当前时间:[" + tmpTimeEnd + "].");
                if (tmpTimeNow >= tmpDayCutTime && (tmpTimeNow < Integer.parseInt(endDateTime.replace(":",""))) && !isRunded) {
                    // 开始执行文件上传任务
                    WriteBankLogLn("开始执行文件上传任务...");
                    String tmpPaySendDate = Format.Date8Format.format(calendar.getTime());
                    String tmpUploadFileName = "YBTRQS" + bankFront.corpNo + "00099" + tmpPaySendDate;
                    String tmpLocalMarkPath = getTempFileDirectory(calendar.getTime()) + File.separator + tmpUploadFileName;
                    WriteBankLogLn("待上传本机批次明细文件路径:" + tmpLocalMarkPath);
                    File tmpLocalMarkFile = new File(tmpLocalMarkPath);
                    if (tmpLocalMarkFile.exists()) {
                        String detailFileMsg = FileHelper.readFileText(tmpLocalMarkPath, getCharset());
                        WriteBankLogLn("开始读取批次明细文件内容，用于读取明细总笔数总金额拼接到汇总文件中,当日批次明细文件内容:\r\n" + detailFileMsg);

                        int totalNum = 0;
                        BigDecimal totalAmt = new BigDecimal("0");

                        StringReader tmpStrReader = new StringReader(detailFileMsg);
                        BufferedReader tmpBuferReader = new BufferedReader(tmpStrReader);
                        while (true) {
                            String eachline = tmpBuferReader.readLine();
                            if (eachline == null) {
                                break;
                            }
                            totalNum++;
                            totalAmt = totalAmt.add(new BigDecimal(StringHelper.amountDivide100(eachline.split("\\|")[3])));
                        }

                        String reqBatchNo = bankFront.corpNo + tmpPaySendDate + "01";
                        String corpNo = bankFront.corpNo + "000";
                        String totalContent = MessageFormat.format("{0}|{1}|{2}|{3}|{4}|{5}|{6}\r\n", reqBatchNo,corpNo,"99",tmpPaySendDate,"S", StringHelper.amountMultiply100(totalAmt.toString()), totalNum);
                        WriteBankLogLn("当日汇总文件内容:" + totalContent);
                        FileHelper.writeFile(tmpLocalMarkPath, totalContent+detailFileMsg, getCharset());

                        // 上送FTP服务器
                        FtpSet ftpSet = bankFront.getFtpSet("bat");
                        String ftpUpFilePath = StringHelper.trimEnd(ftpSet.upDir, "/") + "/" + tmpUploadFileName;
                        WriteBankLogLn("当日批次文件上传FTP服务器路径:" + ftpUpFilePath);
                        FtpReceiver ftpReceiver = null;
                        String requestType = getBankConfig().getValueAsString("requestType");
                        if (requestType != null && "SFTP".equals(requestType)) {
                            SftpPortClient sftpPortClient = new SftpPortClient(ftpSet);
                            String sftpFilePath = StringHelper.trimEnd(ftpSet.upDir, "/") + "/" + tmpUploadFileName;
                            ftpReceiver = sftpPortClient.uploadFile("", tmpLocalMarkPath, sftpFilePath);
                            sftpPortClient.disconnect();
                        } else {
                            FtpPortClient ftpPortClient = new FtpPortClient(ftpSet);
                            ftpReceiver = ftpPortClient.uploadFile(tmpLocalMarkPath, tmpUploadFileName);
                            ftpPortClient.disconnect();
                        }
                        if (!ftpReceiver.isCompleted) {
                            WriteBankLogLn("本机批次代收付文件上传失败，原因:\r\n" + ftpReceiver.connMsg);
                        } else if (ConnState.FAIL.equals(ftpReceiver.connState)) {
                            WriteBankLogLn("本机批次代收付文件上传失败，原因:\r\n" + ConnState.FAIL);
                        } else {
                            WriteBankLogLn("批次批次代收付文件上传成功...\r\n");
                            isRunded = true;
                        }
                    } else {
                        WriteBankLogLn("本机文件:[" + tmpLocalMarkPath + "]不存在,本日无交易，无法执行文件上传任务!");
                    }
                } else {
                    int tmpSpan = tmpDayCutTime - tmpTimeNow;
                    if (tmpSpan > 0) {
                        WriteBankLogLn("定时将于" + (tmpSpan / 60) + "小时后开始执行文件上传任务!");
                    } else {
                        WriteBankLogLn("定时将于" + (tmpSpan / 60 + 24) + "小时后开始执行文件上传任务!");
                    }
                }
            } else {
                WriteBankLogLn("配置文件缺失:'dayCutTime'配置节点，不进行文件上传,请及时更新配置文件!");
            }
        } catch (Exception ex) {
            WriteBankLogLn(ex);
        }
    }
}